package com.czk.netty.netty.groupchat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/18 20:17
 */
public class GroupChatServer {
    /**
     * 监听端口
     */
    private int port;

    /**
     * 构造方法
     *
     * @param port
     */
    public GroupChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        // 创建线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        // 服务器
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 添加处理器 解码器 入站
                        pipeline.addLast("decoder", new StringDecoder());
                        // 添加编码器 出站
                        pipeline.addLast("encoder", new StringEncoder());
                        // 加入自己的handler
                        pipeline.addLast(new GroupChantServerHandler());

                    }
                });
        System.out.println("netty 服务器启动了");
        ChannelFuture channelFuture=null;
        try {
            channelFuture = bootstrap.bind(port).sync();

        } catch (Exception ex) {
            channelFuture.channel().closeFuture().sync();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        GroupChatServer server = new GroupChatServer(7001);
        server.run();
    }
}
